<?php
/**
 * OSS 图片审核
 * User: eks
 * Date: 2023/06/27
 */

namespace App\Tools;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Green\Green;

class OssImgValidate
{
    private $accesskeyid;
    private $accesskeysecret;
    private $endpoint;
    private $bucket;

	public $sDefaultImgUrl = 'https://overseas-files.dalleai.art/default-audit-failure-2.png';


	public $sPath;
	public $iTimeout = 10;
	public $iConnectTimeout = 3;
	//public $aScenes = ['porn', 'terrorism'];
	public $aScenes = ['porn'];

	public $aErrorLabel = [
		'normal' => '正常', 'bloody' => '血腥', 'explosion' => '爆炸烟光', 'outfit' => '特殊装束', 'logo' => '特殊标识',
		'weapon' => '武器', 'politics' => '涉政', 'violence' => '打斗', 'crowd' => '聚众', 'parade' => '游行',
		'carcrash' => '车祸现场', 'flag' => '旗帜', 'location' => '地标', 'drug' => '涉毒', 'gamble' => '赌博', 'others' => '其他'
	];
	public $sErrorLabel;

    public function __construct(){
        $this->accesskeyid = config("oss.accesskeyid");
        $this->accesskeysecret = config("oss.accesskeysecret");
        $this->endpoint = config("oss.endpoint");
        $this->bucket = config("oss.bucket");

		AlibabaCloud::accessKeyClient($this->accesskeyid , $this->accesskeysecret)->timeout($this->iTimeout)
																				  ->connectTimeout($this->iConnectTimeout)->regionId('cn-beijing')->asDefaultClient();
    }

	public function validate($sPath = null) {
		if(empty($sPath)) {
			return '图片URL不能为空';
		}

		$this->sErrorLabel = null;

		$aTask[] = ['dataId' => uniqid(), 'url' => $sPath];
		//$sBizType = $sType == 1 ? 'aipaintersd' : 'aipainter';//业务场景
		$sBizType = 'aipaintersd';//业务场景

		$aParam = ['tasks' => $aTask, 'scenes' => $this->aScenes, 'bizType' => $sBizType];
		$Response = Green::v20180509()->imageSyncScan()->timeout($this->iTimeout)->connectTimeout($this->iConnectTimeout)->body(json_encode($aParam))->request();

		if(200 == $Response->code) {
			foreach($Response->data as $TaskResult) {
				if(200 == $TaskResult->code) {
					foreach($TaskResult->results as $SceneResult) {
						if('pass' != $SceneResult->suggestion) {
							$this->sErrorLabel = $SceneResult->label;
							return false;
						}
					}
				} else {
					return '图片未找到';
				}
			}
			return true;
		}
		return false;
	}
}